package com.vcg.es.test;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import static org.elasticsearch.common.xcontent.XContentFactory.*;

/**
 * Created by wuyu on 2016/9/16.
 */
public class HelloWorld {


    TransportClient client = null;

    @Before
    public void init() throws UnknownHostException {
        client = TransportClient.builder()
                .build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.99.100"), 9300));
    }

    @Test
    public void testCreateIndex() throws IOException {

        JSONObject json = new JSONObject();
        json.put("id", 1);
        json.put("name", "wuyu");
        json.put("address", "安徽省");

        IndexResponse indexResponse = client.prepareIndex("name", "article")
                .setSource(json.toString())
                .get();
        System.err.println(indexResponse.isCreated());
    }

    @Test
    public void testQuery() {
        MultiMatchQueryBuilder query = QueryBuilders.multiMatchQuery("w", "name");
        SearchResponse searchResponse = client.prepareSearch("name")
                .setTypes("article")
                .setHighlighterQuery(query)
                .execute()
                .actionGet();

        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            System.err.println(hit.getScore() + " " + hit.getSource());
        }
    }
}
